package com.loong.common.google.place;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.loong.common.google.configuaration.GoogleConfiguration;
import com.loong.common.google.param.DirectionsParam;
import com.loong.common.google.param.PlaceAutoCompleteParam;
import com.loong.common.google.param.PlaceDetailParam;
import com.loong.common.google.result.*;
import com.loong.common.http.OKHttpUtil;
import com.loong.common.validator.group.CommonValidate;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;

@Component
public class PlaceUtils {

    @Resource
    private GoogleConfiguration googleConfiguration;

    @Resource
    private OKHttpUtil okHttpUtil;

    private final static String BASE_URL = "https://maps.googleapis.com/maps/api/";


    private final static String PLACE_URL = BASE_URL + "place/autocomplete/json?key=%s&input=%s&language=%s";
    private final static String PLACE_DETAIL = BASE_URL + "place/details/json?key=%s&fields=geometry&place_id=%s";
    private final static String DIRECTIONS_DISTANCE = BASE_URL + "directions/json?key=%s&origin=%s&destination=%s";
    /**
     * https://maps.googleapis.com/maps/api/place/autocomplete/json?key=AIzaSyAMgXPi01HWfkSLxSI9zIjko8UTp0GVB-4&input=jazz%20residences&language=en
     *
     * @param
     */
    public List<PlaceAutoCompleteResult> getPlaces(@Validated(value = CommonValidate.class) PlaceAutoCompleteParam param) {
        String url = String.format(PLACE_URL, googleConfiguration.mapConfig().getApiKey(), param.getPlace(), param.getLanguage());
        String result = okHttpUtil.get(url);
        BaseResult baseResult = JSONObject.parseObject(result, BaseResult.class);
        List<PlaceAutoCompleteResult> placeAutoCompleteResults = ((JSONArray) baseResult.getPredictions()).toJavaList(PlaceAutoCompleteResult.class);
        return placeAutoCompleteResults;
    }
    public PlaceDetailResult getPlaceDetail(@Validated(value = CommonValidate.class) PlaceDetailParam placeDetailParam){
        String url = String.format(PLACE_DETAIL, googleConfiguration.mapConfig().getApiKey(), placeDetailParam.getPlaceId());
        String result = okHttpUtil.get(url);
        BaseResult baseResult = JSONObject.parseObject(result, BaseResult.class);
        PlaceDetailResult placeDetailResult = baseResult.getResult().toJavaObject(PlaceDetailResult.class);
        return placeDetailResult;
    }
    /**
     * http://maps.googleapis.com/maps/api/directions/json?key=AIzaSyAMgXPi01HWfkSLxSI9zIjko8UTp0GVB-4&origin=41.43206,-81.38992&destination=42.43206,-82.38992&mode=bicycling
     * 计算距离
     * origin=41.43206,-81.38992
     * destination=42.43206,-82.38992
     *
     * =====mode====出行方式 可能需要计算预计时间 先留着
     * driving （默认）表示使用道路网络的标准行车路线。
     * walking 请求通过人行道和人行道（如果有）的步行路线。
     * bicycling 通过自行车道和首选街道（如果有）请求骑车路线。
     * transit通过公共交通路线（如果有）请求路线。如果将模式设置为transit，则可以选择指定departure_time或 arrival_time。如果未指定任何时间，则 departure_time默认为现在（即，出发时间默认为当前时间）。您还可以选择包含 transit_mode和和/或 transit_routing_preference。
     */
    public DistanceDurationResult getDistance(DirectionsParam param){
        String origin = param.getShopLat()+",-"+param.getShopLng();
        String destination = param.getUserLat()+",-"+param.getUserLng();
        String url = String.format(DIRECTIONS_DISTANCE, googleConfiguration.mapConfig().getApiKey(), origin,destination);
        String result = okHttpUtil.get(url);
        DirectionsResult directionsResult = JSONObject.parseObject(result, DirectionsResult.class);
        List<DirectionsLegsResult> directionsLegsResults = ((JSONArray) directionsResult.getRoutes()).toJavaList(DirectionsLegsResult.class);
        JSON legs = directionsLegsResults.get(0).getLegs();
        List<DirectionStepsResult> directionStepsResults = ((JSONArray) legs).toJavaList(DirectionStepsResult.class);
        DirectionStepsResult directionStepsResult = directionStepsResults.get(0);
        JSONArray steps = (JSONArray)directionStepsResult.getSteps();
        DirectionsDistanceResult directionsDistanceResult = steps.toJavaList(DirectionsDistanceResult.class).get(0);
        DistanceDurationResult distanceResult = directionsDistanceResult.getDistance().toJavaObject(DistanceDurationResult.class);
        return distanceResult;
    }

//    public static void main(String[] args) {
//        String str = "{\"status\":\"OK\",\"routes\":[{\"summary\":\"I-40 W\",\"legs\":[{\"steps\":[{\"travel_mode\":\"DRIVING\",\"start_location\":{\"lat\":41.8507300,\"lng\":-87.6512600},\"duration\":{\"value\":19,\"text\":\"1 min\"},\"distance\":{\"value\":207,\"text\":\"0.1 mi\"}}]}]}]}";
//        DirectionsResult directionsResult = JSONObject.parseObject(str, DirectionsResult.class);
//        System.out.println(((JSONArray)directionsResult.getRoutes()).toJavaList(DirectionsLegsResult.class));
//        List<DirectionsLegsResult> directionsLegsResults = ((JSONArray) directionsResult.getRoutes()).toJavaList(DirectionsLegsResult.class);
//        JSON legs = directionsLegsResults.get(0).getLegs();
//        System.out.println(((JSONArray)legs).toJavaList(DirectionStepsResult.class));
//        List<DirectionStepsResult> directionStepsResults = ((JSONArray) legs).toJavaList(DirectionStepsResult.class);
//        DirectionStepsResult directionStepsResult = directionStepsResults.get(0);
//        JSONArray steps = (JSONArray)directionStepsResult.getSteps();
//        System.out.println(steps.toJavaList(DirectionsDistanceResult.class));
//        DirectionsDistanceResult directionsDistanceResult = steps.toJavaList(DirectionsDistanceResult.class).get(0);
//        System.out.println(( directionsDistanceResult.getDistance().toJavaObject(DistanceDurationResult.class)));
//        System.out.println(( directionsDistanceResult.getDuration().toJavaObject(DistanceDurationResult.class)));
//    }



}

